#!/bin/bash
#初始化远程终端

error_exit(){
	echo "ERROR:初始化远程终端失败, $1"
	exit 1
}

sshIp=$1
sshUser=$2
sshPass=$3
sshRootPass=$4
port=$5
#远程终端用户组 java为tomcat,php为apache
sshNewGroup=$6
sshTomcatPath=$7

sshNewUser="beetle"
#当前beetle机器登录用户名
loginUser=`whoami`

shellPath=`pwd`
echo "==========初始化远程终端开始=========="
#拷贝脚本文件
echo "==========拷贝文件beetle_terminal_user_create.sh开始=========="
expect beetle_terminal_scp.sh ${port} ${sshIp} ${sshUser} ${sshPass} ${shellPath}/beetle_terminal_user_create.sh /home/${sshUser}/ || error_exit "拷贝文件beetle_terminal_user_create.sh失败"
echo "==========拷贝文件beetle_terminal_user_create.sh结束=========="

echo "==========拷贝文件id_rsa.pub开始=========="
expect beetle_terminal_scp.sh ${port} ${sshIp} ${sshUser} ${sshPass} /usr/local/Beetle/ssh/id_rsa.pub /home/${sshUser}/ || error_exit "拷贝文件id_rsa.pub失败"
echo "==========拷贝文件id_rsa.pub结束=========="


echo "==========初始化用户${sshNewUser}开始=========="
expect beetle_terminal_user_init.sh ${port} ${sshIp} ${sshUser} ${sshPass} ${sshRootPass} ${sshNewUser} ${sshNewGroup} || error_exit "远程机创建用户失败"
echo "==========初始化用户${sshNewUser}结束=========="

echo "==========校验ssh免密登录开始=========="
expect beetle_validate_ssh.sh ${sshIp} ${sshNewUser} ${loginUser} ${port} || error_exit "校验ssh免密登录失败"
echo "==========校验ssh免密登录结束=========="


if [ ${sshTomcatPath} ]
then
    echo "==========拷贝文件beetle_release_tomcat_log.sh开始=========="
    expect beetle_terminal_dir.sh ${sshIp} ${sshRootPass} ${sshNewUser} ${loginUser} ${sshTomcatPath} ${sshNewGroup} ${port} || error_exit "修改tomact目录权限失败"
    scp -P ${port} -i /home/${loginUser}/.Beetle/common_id_rsa ${shellPath}/beetle_release_tomcat_log.sh ${sshNewUser}@${sshIp}:${sshTomcatPath}/ || error_exit "拷贝文件beetle_release_tomcat_log.sh失败"
    ssh -p ${port} -i /home/${loginUser}/.Beetle/common_id_rsa ${sshNewUser}@${sshIp} "cd ${sshTomcatPath};chmod +x beetle_release_tomcat_log.sh" || error_exit "beetle_release_tomcat_log.sh赋权失败"
    scp -P ${port} -i /home/${loginUser}/.Beetle/common_id_rsa ${shellPath}/tomcat.sh ${sshNewUser}@${sshIp}:${sshTomcatPath}/ || error_exit "tomcat.sh失败"
    ssh -p ${port} -i /home/${loginUser}/.Beetle/common_id_rsa ${sshNewUser}@${sshIp} "cd ${sshTomcatPath};chmod +x tomcat.sh" || error_exit "tomcat.sh赋权失败"
    echo "==========拷贝文件beetle_release_tomcat_log.sh结束=========="
fi

echo "==========初始化远程终端成功=========="